package com.example.hcd.functionactivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.example.hcd.R;
import com.example.hcd.internet.FileUtils;
import com.example.hcd.tool.DragImageView;
import com.example.hcd.tool.MyLoadingDialog;
import com.example.hcd.tool.ToastHelp;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.Toast;

public class FileDetailActivity extends BaseActivity
{
	String uri=null;

    String name=null;
	DragImageView image;

	private int window_width;

	private int window_height;

	private GestureDetector gestureScanner;
	
	private MyLoadingDialog dialog;
	
	private boolean is_bendi = false;
	
	private Context context;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mPageName = "FileDetailActivity";
		context  =this;
		setContentView(R.layout.activity_file_display_page);
		uri = getIntent().getStringExtra("FILE_URI");
		name = getIntent().getStringExtra("FILE_NAME");
		is_bendi = getIntent().getBooleanExtra("IS_BENDI", is_bendi);
		
		initView();
	}
	
	private class LoadTaskInfoList extends AsyncTask<String, Integer, String> {

		private Context context;
		private String urlStr;
		private String path;
		private String fileName;
		public LoadTaskInfoList(Context context,String uri,String lujing,String name) {
			this.context = context;
			urlStr = uri;
			path = lujing;
			fileName =name;
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected String doInBackground(String... params) {
			
			String errorId = "-1";
			try {
				URL url = new URL(urlStr);
				
				URLConnection coon = url.openConnection();
				// 取得inputStream，并将流中的信息写入SDCard

				/*
				 * 写前准备 1.在AndroidMainfest.xml中进行权限配置 <uses-permission
				 * android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
				 * 取得写入SDCard的权限 2.取得SDCard的路径：
				 * Environment.getExternalStorageDirectory() 3.检查要保存的文件上是否已经存在
				 * 4.不存在，新建文件夹，新建文件 5.将input流中的信息写入SDCard 6.关闭流
				 */
				String pathName = path + "/" + fileName;
				File file = new File(path);
				InputStream input = coon.getInputStream();

				if (!file.exists()) {
					file.mkdirs();
				}

				File files = new File(pathName);

				if (files.exists()) {
					errorId = "1";
				} else {
					//files.createNewFile();
					FileOutputStream output = new FileOutputStream(pathName);
					// 读取到的数据长度   
			        int len; 
					// 读取大文件
					byte[] buffer = new byte[4 * 1024];
					while ((len = input.read(buffer)) != -1) {
						output.write(buffer,0,len);
					}
//					output.flush();
					output.close();
					input.close();
					errorId = "0";

				}

			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {

			}
			dialog.dimiss();
			return errorId;
		}

		@Override
		protected void onPostExecute(String result) {
	        if(result.equals("-1"))
	        {
	        	dialog.dimiss();
	        	ToastHelp.doToastInTop(FileDetailActivity.this, "下载失败");
	        	finish();
	        }else
	        {
	        	dialog.dimiss();
	        	Toast.makeText(FileDetailActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
	        	openFile(Environment.getExternalStorageDirectory()+"/venadaOA/"+getLast(name));
	        	
	        }
		}

	}
	
	
	private void initView()
	{
		if(FileUtils.isPic(name))
		{
			dialog = new MyLoadingDialog(this, null, "加载中...", false);
			showPic();
		}else
		{
			dialog = new MyLoadingDialog(this, null, "下载中...", false);
			showtext();
		}
		
	}
	
	private String getLast(String path)
    {
    	String a[] = path.split("/");
    	return a[a.length-1];
    }
	
	private void showtext()
	{ 
		if(is_bendi)
		{
			openFile(uri);
			return;
		}
		
		new LoadTaskInfoList(context,uri,Environment.getExternalStorageDirectory()+"/venadaOA",getLast(name)).execute();
  
	}
	
	private void openFile(String url)
	{
		dialog.dimiss();
		String filename = getLast(name);
		Intent intent=null;
		if(filename.endsWith(".txt")||filename.endsWith(".TXT"))
		{
			intent = getTextFileIntent(url, false);
		}else if(filename.endsWith(".html")||filename.endsWith(".HTML"))
		{
			intent = getHtmlFileIntent(url);
		}else if(filename.endsWith(".pdf")||filename.endsWith(".PDF"))
		{
			intent = getPdfFileIntent(url);
		}else if(filename.contains(".doc")||filename.contains(".DOC"))
		{
			intent = getWordFileIntent(url);
		}else if(filename.contains(".xls")||filename.contains(".XLS"))
		{
			intent = getExcelFileIntent(url);
		}else if(filename.endsWith(".ppt")||filename.endsWith(".PPT"))
		{
			intent = getPptFileIntent(url);
		}else if(filename.endsWith(".avi")||filename.endsWith(".AVI")||filename.endsWith(".mp4")||filename.endsWith(".mp4")||filename.endsWith(".MP4")||filename.endsWith(".AVI")||filename.endsWith(".mov")||filename.endsWith(".MOV"))
		{
			intent = getVideoFileIntent(url);
		}else if(filename.endsWith(".mp3")||filename.endsWith(".MP3"))
		{
			intent = getAudioFileIntent(url);
		}else
		{
			//Toast.makeText(this, "不支持的预览格式", Toast.LENGTH_SHORT).show();
			ToastHelp.doToastInTop(this, "不支持的预览格式");
			finish();
			return;
		}
		
		startActivity(intent);
		finish();
	}

	
	private void showPicBendi()
	{
		dialog.dimiss();
		try {
		image = new DragImageView(this);
		image.setmActivity(this);
		/* 获取可見区域高度 */
		WindowManager manager = getWindowManager();
		window_width = manager.getDefaultDisplay().getWidth();
		window_height = manager.getDefaultDisplay().getHeight();
		/* 设置图片的高宽，和屏幕相同 */
		image.setLayoutParams(new LinearLayout.LayoutParams(window_width,
				window_height));
		/* 无边距填充 */
		image.setPadding(0, 0, 0, 0);
		/* 图片居中，这个主要是我在缩放的时候，缩小的情况小看着好看一点 */
		image.setScaleType(ScaleType.FIT_CENTER);
		setContentView(image);
		
		BitmapFactory.Options options = new BitmapFactory.Options();  
        options.inSampleSize = 1;  
        Bitmap bitmap = BitmapFactory.decodeFile(uri, options);  

        if(bitmap!=null)
        {
        	image.setImageBitmap(bitmap);
        }else
        {
        	image.setImageResource(R.drawable.image);
        }
        
        } catch (Exception e) { 
            e.printStackTrace();
            finish();
        } 
		
	}
	
	private void showPic()
	{
		if(is_bendi)
		{
			showPicBendi();
			return;
		}
		//image = (DragImageView)findViewById(R.id.imageView1);
		/* 加载图片 */
		
		image = new DragImageView(this);
		image.setmActivity(this);
		/* 获取可見区域高度 */
		WindowManager manager = getWindowManager();
		window_width = manager.getDefaultDisplay().getWidth();
		window_height = manager.getDefaultDisplay().getHeight();
		/* 设置图片的高宽，和屏幕相同 */
		image.setLayoutParams(new LinearLayout.LayoutParams(window_width,
				window_height));
		/* 无边距填充 */
		image.setPadding(0, 0, 0, 0);
		/* 图片居中，这个主要是我在缩放的时候，缩小的情况小看着好看一点 */
		image.setScaleType(ScaleType.FIT_CENTER);
		setContentView(image);
		ImageLoader.getInstance().displayImage(uri, image, new ImageLoadingListener() {
			
			@Override
			public void onLoadingStarted(String arg0, View arg1)
			{
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onLoadingFailed(String arg0, View arg1, FailReason arg2)
			{
				// TODO Auto-generated method stub
				dialog.dimiss();
				//Toast.makeText(FileDetailActivity.this, "图片加载失败", Toast.LENGTH_SHORT).show();
				ToastHelp.doToastInTop(FileDetailActivity.this, "图片加载失败");
			}
			
			@Override
			public void onLoadingComplete(String arg0, View arg1, Bitmap arg2)
			{
				// TODO Auto-generated method stub
				dialog.dimiss();
				Toast.makeText(FileDetailActivity.this, "图片加载成功", Toast.LENGTH_SHORT).show();
			}
			
			@Override
			public void onLoadingCancelled(String arg0, View arg1)
			{
				// TODO Auto-generated method stub
				dialog.dimiss();
				ToastHelp.doToastInTop(FileDetailActivity.this, "图片加载失败");
				
			}
		});
	

	}
	long firClick = -1;
    long secClick;
   @Override
   public boolean onTouchEvent(MotionEvent event) {
	// TODO Auto-generated method stub
	   if (event.getAction() == MotionEvent.ACTION_DOWN) 
	   {
			
           secClick = System.currentTimeMillis();
           if (secClick - firClick < 1000) {
               finish();
               //overridePendingTransition(R.anim.out_alpha, R.anim.enter_alpha);
           }else
           {
           	firClick = secClick;
           }
	
	   	}
	   
	   return super.onTouchEvent(event);
   }
   
 //android获取一个用于打开HTML文件的intent
   public static Intent getHtmlFileIntent(String param )
   {
     Uri uri = Uri.parse(param).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(param).build();
     Intent intent = new Intent("android.intent.action.VIEW");
     intent.setDataAndType(uri,"text/html");
     return intent;
   }
  
 //android获取一个用于打开图片文件的intent
   public static Intent getImageFileIntent(String param )
   {
     Intent intent = new Intent("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     Uri uri = Uri.fromFile(new File(param ));
     intent.setDataAndType(uri,"image/*");
     return intent;
   }
  
   //android获取一个用于打开PDF文件的intent
   public static Intent getPdfFileIntent( String param )
   {
     Intent intent = new Intent("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     Uri uri = Uri.fromFile(new File(param ));
     intent.setDataAndType(uri,"application/pdf");
     return intent;
   }
  
 //android获取一个用于打开文本文件的intent
  public static Intent getTextFileIntent( String param, boolean paramBoolean)
 {
  Intent intent = new Intent("android.intent.action.VIEW");
  intent.addCategory("android.intent.category.DEFAULT");
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  if (paramBoolean)
  {
 Uri uri1 =Uri.parse(param );
 intent.setDataAndType(uri1,"text/plain");
  }
  else
  {
 Uri uri2 =Uri.fromFile(new File(param ));
 intent.setDataAndType(uri2,"text/plain");
  }
  
  return intent;
 }
  
 //android获取一个用于打开音频文件的intent
   public static Intent getAudioFileIntent(String param )
   {
     Intent intent = new Intent("android.intent.action.VIEW");
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
     intent.putExtra("oneshot", 0);
     intent.putExtra("configchange",0);
     Uri uri = Uri.fromFile(new File(param ));
     intent.setDataAndType(uri,"audio/*");
     return intent;
   }
  
   //android获取一个用于打开视频文件的intent
   public static Intent getVideoFileIntent(String param )
   {
     Intent intent = new Intent("android.intent.action.VIEW");
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
     intent.putExtra("oneshot", 0);
     intent.putExtra("configchange",0);
     Uri uri = Uri.fromFile(new File(param ));
     intent.setDataAndType(uri,"video/*");
     return intent;
   }
  
   //android获取一个用于打开CHM文件的intent
   public static Intent getChmFileIntent( String param )
   {
     Intent intent = new Intent("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     Uri uri = Uri.fromFile(new File(param ));
     intent.setDataAndType(uri,"application/x-chm");
     return intent;
   }
  
 //android获取一个用于打开Word文件的intent
   public static Intent getWordFileIntent(String param )
   {
     Intent intent = new Intent("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     Uri uri = Uri.fromFile(new File(param ));
     intent.setDataAndType(uri,"application/msword");
     return intent;
   }
  
 //android获取一个用于打开Excel文件的intent
   public static Intent getExcelFileIntent(String param )
   {
     Intent intent = new Intent("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     Uri uri = Uri.fromFile(new File(param ));
     intent.setDataAndType(uri,"application/vnd.ms-excel");
     return intent;
   }
  
 //android获取一个用于打开PPT文件的intent
   public static Intent getPptFileIntent( String param )
   {
     Intent intent = new Intent("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     Uri uri = Uri.fromFile(new File(param ));
     intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
     return intent;
   }
    
	
	

}
